#!/bin/bash
# install tomcat
# before install tomcat,you need install java,and config env variable
set -u -e
JAVA_HOME=/usr/local/jdk
TOMCAT_PACK="apache-tomcat-9.0.89.tar.gz"
INSTALL_DIR="/usr/local"



CURRENT_DIR="$(pwd)"

color() {
    local message="$1"
    local status="$2"
    local message_length=${#message}
    local terminal_width=$(tput cols)
    local middle_column=$(( terminal_width / 2))
    local SETCOLOR_SUCCESS="\033[1;32m"  # 绿色
    local SETCOLOR_FAILURE="\033[1;31m"  # 红色
    local SETCOLOR_WARNING="\033[1;33m"  # 黄色
    local SETCOLOR_NORMAL="\033[0m"      # 重置颜色
    printf '%s\n\033[%sG' "$message"  "$middle_column"
    # Print the status message
    printf "["
    case $status in
        success|0)
            printf "$SETCOLOR_SUCCESS"
            printf "  OK  "
            ;;
        failure|1)
            printf "$SETCOLOR_FAILURE"
            printf "FAILED"
            ;;
        *)
            printf "$SETCOLOR_WARNING"
            printf "WARNING"
            ;;
    esac
    printf "$SETCOLOR_NORMAL"
    printf "]\n"
}

if [ -e ${JAVA_HOME} ] &&  ${JAVA_HOME}/bin/java -version &> /dev/null  ;then
	color "java环境可用！" 0
else
	color "指定的java环境不存在！" 1
	exit
fi



if [ -d ${INSTALL_DIR}/apache-tomcat ];then
	color "${INSTALL_DIR} 已存在tomcat目录！！" 1
	exit
else
	[ -d ${INSTALL_DIR} ] || { mkdir -p ${INSTALL_DIR};color "发现${INSTALL_DIR}目录不存在,创建该目录." 0;}
	
	if id tomcat &> /dev/null;then
		color "tomcat用户已存在，不在创建tomcat用户" 2
	else
		color "tomcat用户不存在，创建tomcat用户..." 2
		useradd -M -r -s /sbin/nologin tomcat
	fi
	tar  -xf $TOMCAT_PACK -C $INSTALL_DIR
	cd $INSTALL_DIR;ln -s apache-tomcat* tomcat;chown -R tomcat:tomcat  *tomcat*;cd $CURRENT_DIR
	cat > /etc/systemd/system/tomcat.service <<-EOF
	[Unit]
	Description=Tomcat
	After=syslog.target network.target
	
	[Service]
	Type=forking
	Environment=JAVA_HOME=${JAVA_HOME}
	ExecStart=${INSTALL_DIR}/tomcat/bin/startup.sh
	ExecStop=${INSTALL_DIR}/tomcat/bin/shutdown.sh
	PrivateTmp=true
	User=tomcat
	Group=tomcat
	
	[Install]
	WantedBy=multi-user.target
	EOF
	systemctl daemon-reload
	systemctl enable --now tomcat.service && color "tomcat 启动成功" 0
fi



